import 'dart:io';

import 'package:flutter_test/flutter_test.dart';
import 'package:pd_log/src/log_file_info.dart';
import 'package:pd_log/src/log_ledger.dart';

void main() {
  group('LogLedger snapshot and deletion', () {
    late Directory tempRoot;

    setUp(() {
      tempRoot = Directory.systemTemp.createTempSync('pd_log_ledger_test');
      LogLedger.setTestOverrideRoot(tempRoot.path);
    });

    tearDown(() {
      try {
        tempRoot.deleteSync(recursive: true);
      } catch (_) {}
      LogLedger.setTestOverrideRoot(null);
    });

    test('syncFromFiles creates snapshot entries', () async {
      final path1 =
          '${tempRoot.path}${Platform.pathSeparator}2025${Platform.pathSeparator}10${Platform.pathSeparator}01.log';
      final path2 =
          '${tempRoot.path}${Platform.pathSeparator}2025${Platform.pathSeparator}11${Platform.pathSeparator}01.log';
      // Build files with actual paths
      final f1 = PDLogFile(path: path1, sizeBytes: 1234, modifiedMs: 1000);
      final f2 = PDLogFile(path: path2, sizeBytes: 5678, modifiedMs: 2000);
      await LogLedger.syncFromFiles([f1, f2]);

      final summary = await LogLedger.listSummary();
      expect(summary.length, 2);
      final r1 = summary.firstWhere((e) => e.path == path1);
      final r2 = summary.firstWhere((e) => e.path == path2);
      expect(r1.exists, isTrue);
      expect(r2.exists, isTrue);
      expect(r1.sizeBytes, 1234);
      expect(r2.sizeBytes, 5678);
      expect(r1.year, 2025);
      expect(r1.month, 10);
      expect(r2.month, 11);
    });

    test('recordDeletion updates snapshot to exists=false', () async {
      final path1 =
          '${tempRoot.path}${Platform.pathSeparator}2025${Platform.pathSeparator}10${Platform.pathSeparator}01.log';
      final path2 =
          '${tempRoot.path}${Platform.pathSeparator}2025${Platform.pathSeparator}11${Platform.pathSeparator}01.log';
      final f1 = PDLogFile(path: path1, sizeBytes: 1, modifiedMs: 1000);
      final f2 = PDLogFile(path: path2, sizeBytes: 1, modifiedMs: 2000);
      await LogLedger.syncFromFiles([f1, f2]);

      await LogLedger.recordDeletion(path1);
      final summary = await LogLedger.listSummary();
      final r1 = summary.firstWhere((e) => e.path == path1);
      final r2 = summary.firstWhere((e) => e.path == path2);
      expect(r1.exists, isFalse);
      expect(r1.deletedMs, isNotNull);
      expect(r2.exists, isTrue);
    });
  });
}
